import re
import json
import time
import random
import openpyxl
import requests
import argparse
from lxml import etree
from hashlib import md5
from openpyxl.styles import Font, Border, Side, Alignment
from bs4 import BeautifulSoup
from openai import OpenAI

def trans_by_deepseek(word : str):
    client = OpenAI(api_key="sk-c8de13144cf64499a75b2741b0d75a88", base_url="https://api.deepseek.com")
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "你是一本英汉词典."},
            {"role": "user", "content": "请用 发音:[xxx] 含义:xxx 的格式返回 %s 的英式发音音标和常用中文含义(有几个写几个,逗号分隔)" % word}
        ]
    )
    if response:
        ret = response.choices[0].message.content
        patterns = {
            'pron': r'发音:([^\n]+)',          # 匹配"发音："后面直到换行的内容
            'mean': r'含义:([^\n]+)'           # 匹配"含义："后面直到换行的内容
        }
    
        result = {}
        for key, pattern in patterns.items():
            # 查找匹配项
            match = re.search(pattern, ret)
            # 如果找到匹配项则提取内容，否则为None
            result[key] = match.group(1).strip() if match else None
        return result
    return None

parser = argparse.ArgumentParser(description='读取文件名')
parser.add_argument('--file', type=str, help='要处理的文件名')
parser.add_argument('--word', type=str, help='要查找的单词')
args = parser.parse_args()
filename = ""
if args.file:
    filename = args.file
else:
    filename = '初一英语单词.xlsx'

if args.word:
    print(trans_by_deepseek(args.word))
    exit()
    
workbook = openpyxl.load_workbook(filename)
list_words = set()

sheet = workbook.active
for row_num in range(2, 3000):
    word = sheet.cell(row_num, 4).value
    mean = sheet.cell(row_num, 1).value
    if(word == None):
        break
    if mean == None:
        print("正在处理第 %d 个单词: %s" % (row_num, word) , end="")
        result = trans_by_deepseek(word)
        if result:
            if 'mean' in result and 'pron' in result:
                sheet.cell(row=row_num, column=1).value = result['mean']
                sheet.cell(row=row_num, column=3).value = result['pron']
                print(" 成功")
            if word in list_words:
                print("==============>第 %d 个单词(%s)重复了" % (row_num, word))
            else:
                list_words.add(word)
        else:
            print(" 失败")
    
workbook.save(filename)